package com.orangelife.mobile.main.fragment;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.curry.android.http.OrangeDataHandler;
import com.curry.android.http.OrangeErrorHandler;
import com.curry.android.http.VolleyHttpUtil;
import com.curry.orangelife.mobile.R;
import com.datatrack.DataTrack;
import com.google.gson.reflect.TypeToken;
import com.common.jump.MessageJumper;
import com.orangelife.mobile.main.biz.MainHttpBz;
import com.orangelife.mobile.util.BLog;
import com.orangelife.mobile.widget.textview.UpMarqueeTextView;

import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 首页纵向文字跑马灯界面
 * <p>
 * Created by cx on 2015/11/12.Modify by wgf on 160715.
 *
 * @author cx
 */
public class RollAdsFragment extends Fragment {

    View homePageView;
    @Bind(R.id.tvMarquee)
    UpMarqueeTextView mMarqueeTextView;
    @Bind(R.id.ivJumpAll)
    ImageView ivJumpAll;
    List<Map<String, Object>> listmap;

    private int isOk = 0;

    public RollAdsFragment() {
        super();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (homePageView == null) {
            homePageView = inflater.inflate(R.layout.fragment_rollads,
                    container, false);
            ButterKnife.bind(this, homePageView);
            findView();
            requestAllAds();
        }
        ViewGroup parent = (ViewGroup) homePageView.getParent();
        if (parent != null) {
            parent.removeView(homePageView);
        }
        return homePageView;
    }

    private List names = new ArrayList<>();
    private int index = 0;

    private void findView() {
        if (mRefreshAdRunnable != null) {
            mRefreshAdRunnable.run();
        }
        mMarqueeTextView.setOnClickListener(listener);
        ivJumpAll.setOnClickListener(listener);
        //首次进入清除轮播信息
        if (names.size() > 0) {
            names.clear();
            isOk = 0;
        }
    }

    public void requestAllAds() {
        MainHttpBz.getAllads(new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject jsonObject, int i) {
                index = 0;
                if (names.size() > 0) {
                    names.clear();
                    isOk = 0;
                }
                if (OrangeErrorHandler.getInstance().isSuccess(jsonObject,false)) {
                    listmap = OrangeDataHandler.getListFromJsonWithPageEntity(jsonObject, new TypeToken<List<Map<String, Object>>>() {
                    }.getType(), null, null);
                    if (listmap != null) {
                        Map<String, String> rollmap = new HashMap<>();
                        for (Map<String, Object> map : listmap) {
                            rollmap.put(map.get("title").toString(), map.get("content").toString());
                            names.add(map.get("title").toString());
                        }
                    }
                }
            }
        });
    }

    private View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.tvMarquee:
                    //判断公告有信息才能点击到详情界面
                    if (names.size() > 0 && isOk == 1) {
                        String url = String.valueOf(mMarqueeTextView.getValue().get("url"));
                        String annoID = String.valueOf(mMarqueeTextView.getValue().get("annoID"));
                        MessageJumper.jumpToAnnouncementDetail(getActivity(), url, annoID, true, null);
                        dataTrack(String.valueOf(mMarqueeTextView.getValue().get("title")));
                    }
                    break;
                case R.id.ivJumpAll:
                    MessageJumper.jumpToAnnouncementList(getActivity());
                    break;
            }
            BLog.getInstance().click(BLog.MESSAGE);
        }
    };

    private void dataTrack(String title){
        Map<String,Object> map=new HashMap<>();
        map.put("announceName",title);
        DataTrack.clickTrack("lableAnnounce",map);
    }
    /**
     * 延时启动广告线程
     */
    private final MyHandler<FragmentActivity> mRefreshAdHandler = new MyHandler<>(getActivity());
    /**
     * 取本地广告线程
     */
    private Runnable mRefreshAdRunnable = new Runnable() {
        @Override
        public void run() {
            String text = null;
            if (names.size() > 0 && index < names.size()) {
                text = names.get(index).toString();
                mMarqueeTextView.setValue(listmap.get(index));
                isOk = 1;
            }
            index++;
            if (index > names.size() - 1) {
                index = 0;
            }
            if (text != null && !"".equals(text))
                mMarqueeTextView.setText(text);

            // 每隔多长时间执行一次

            mRefreshAdHandler.postDelayed(mRefreshAdRunnable, 1000 * 6);

        }
    };

    static class MyHandler<T> extends Handler {
        WeakReference<T> mActivity;

        MyHandler(T activity) {
            mActivity = new WeakReference<T>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            T theActivity = mActivity.get();
            if (theActivity != null) {

            }
        }
    }
}
